/* 
 * cms，一个基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department:运营department
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.action.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.grayrabbit.cms.action.common.AuthCheckAction;
import org.grayrabbit.cms.action.common.BaseAction;
import org.grayrabbit.cms.constant.ConstantOperCode;
import org.grayrabbit.cms.constant.ConstantWebApp;
import org.grayrabbit.cms.constant.ConstantEnum.Module;
import org.grayrabbit.cms.constant.ConstantEnum.OperAct;
import org.grayrabbit.cms.entity.Admin;
import org.grayrabbit.cms.entity.AdminOperRela;
import org.grayrabbit.cms.entity.OperCode;
import org.grayrabbit.cms.entity.Role;
import org.grayrabbit.cms.entity.RoleOperRela;
import org.grayrabbit.cms.service.system.AdminOperRelaService;
import org.grayrabbit.cms.service.system.AdminService;
import org.grayrabbit.cms.service.system.OperCodeService;
import org.grayrabbit.cms.service.system.RoleOperRelaService;
import org.grayrabbit.cms.service.system.RoleService;
import org.grayrabbit.cms.util.OperCodeJSONUtil;
import org.grayrabbit.cms.vo.system.OperCodeBean;
import org.grayrabbit.cms.vo.system.OperCodeCheckBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import org.grayrabbit.dao.util.Page;

/**
 * <b>OperCodeAction</b> Struts2 action�?





 * @version 1.0,创建时间:2011-05-16 15:55:06 
 */
@Controller
@Scope("prototype")
public class OperCodeAction extends BaseAction<OperCodeBean> implements AuthCheckAction{
	private static final long serialVersionUID = -1L;
	//Service接口接入
	@Autowired
	@Qualifier("operCodeServiceImpl")
	private OperCodeService operCodeService;
	
	@Autowired
	@Qualifier("roleServiceImpl")
	private RoleService roleService;
	
	@Autowired
	@Qualifier("adminServiceImpl")
	private AdminService adminService;
	
	@Autowired
	@Qualifier("roleOperRelaServiceImpl")
	private RoleOperRelaService roleOperRelaService;
	
	@Autowired
	@Qualifier("adminOperRelaServiceImpl")
	private AdminOperRelaService adminOperRelaService;
 
	private String objectType; 
	private String objectId;
	private String authJsonText; 
	private String jsonText;
	
	//VO对象，由前端页面数据组装
	private OperCodeBean operCode;
	private List<List<OperCode>> codeList = new ArrayList<List<OperCode>>();
	
	/**return 前端页面数据组装VO对象,<b>OperCodeBean</b>*/
	public OperCodeBean getOperCode() {
		return operCode;
	}
	
	public void setOperCode(OperCodeBean operCode) {
		this.operCode = operCode;
	}
	
	//分页对象
	private Page<OperCode> page = new Page<OperCode>(MAX_PAGE_NUM,true);
	
	/*
	 * return分页对象，默认实例化。如：page.pageNu=2,将更新相应的对象property
	 */
	public Page<OperCode> getPage() {
		return page;
	}
	//接收前端form,url提交参数组装成分页property
	public void setPage(Page<OperCode> page) {
		this.page = page;
	}
	
	/**
	 * 在执行（struts2的action调用时）list()方法前执行本方法
	 */
	public void prepareList(){
		prepareModel();
	}
	
	/**
	 * 在执行任何其它action方法（struts2的action调用时）前执行本方法
	 */
	public void prepare(){
		if(operCode==null){
			operCode = new OperCodeBean();
		}
	}
	/**
	 * 实现ModelDriven的接口简例前端页的bean组装写法,
	 *  如：
	 *	<pre>
	 *		<code> name="user.userName"</code>
	 *	改写成：
	 *		<code> name="userName"</code>
	 *	action实例中，会自动组成user成员变量
	 *	</pre>
	 */
	public OperCodeBean getModel() {
		return operCode;
	}
	
	@Override
	protected void prepareModel(){
		if(operCode != null &&StringUtils.isNotBlank(operCode.getOperId())){
			operCode = (OperCodeBean)dozer.map(operCodeService.getOperCode(operCode.getOperId()),OperCodeBean.class);
		}
		
	}

	/**
	 * 删除<b>OperCode</b>记录的方法，成员变量<b>key</b>为主键的String数组，以主键方式进行删作
	 * 删除成功后，返回"reload"，然后跳转到opercode-list.action
	 */
	public String delete(){
 
		return RELOAD;
	}
	
	@Override
	@Action(value="opercode-list")
	public String list(){
		codeList =operCodeService.findAllAreaCodes();
		if(StringUtils.isNotBlank(objectId) && StringUtils.isNotBlank(objectType) ){
			if(ConstantWebApp.OPER_CODE_ROLE.equals(objectType)){ 
				authJsonText = roleOperRelaService.wrapAuthJsonText(objectId);
				Role role = roleService.getRole(objectId);
				jsonText=role.getRoleName();
			}else if(ConstantWebApp.OPER_CODE_ADMIN.equals(objectType)){ 
				authJsonText = adminOperRelaService.wrapAuthJsonText(objectId);
				Admin admin = adminService.getAdmin(objectId);
				jsonText=admin.getLoginName();
			}
		}
		return SUCCESS;
	}
	/**
	 * OperCode的新增与编辑的方法执行成功能
	 * 将映射到opercode-input.jsp
	 */
	public String input(){
	    
		return SUCCESS;
	}
	
	/**
	 * save or update OperCode的方法，将成员property operCode转成OperCode实例，执行保存；
	 * 执行成功后，返回"reload"，然后跳转到opercode-list.action
	 */
	public String save(){
		OperCode obj = (OperCode) dozer.map(operCode, OperCode.class);
		if(!StringUtils.isNotBlank(obj.getOperId())){
			obj.setOperId(null);
		}
		operCodeService.save(obj);
		return RELOAD;
	}
	/**
	 *  存储权限信息  
	 * @param   ObjectId  管理员/角色ID   ObjectType 管理员/角色（判别类别 admin/role）
	 * @return  存储结果
	 */
	@Action(value="opercode-auth")
	public String saveAuthCode(){
		if(StringUtils.isNotBlank(objectType) && ConstantWebApp.OPER_CODE_ROLE.equals(objectType)){
//			roleOperRelaService.saveAllAuthCodeByRoleId(objectId,objectType,authJsonText);
			
			roleOperRelaService.deleteRoleAuth(objectId);
			List<RoleOperRela> list = OperCodeJSONUtil.getRoleAuth(authJsonText, objectId, objectType);
			List<RoleOperRela> cats = new ArrayList<RoleOperRela>();
			List<RoleOperRela> others = new ArrayList<RoleOperRela>();
			for(RoleOperRela re: list){
				if(ConstantOperCode.AUTH_CAT_TYPE.equals(re.getOperTargetType())){
					cats.add(re);
				}else{
					others.add(re);
				}
			}
			roleOperRelaService.save(others);
			roleOperRelaService.save(cats);			
			jsonText = "{flag:true,msg:'\u89d2\u8272\u6743\u9650\u8c03\u6574\u6210\u529f'}";
			addLog(Module.SYSTEM.getValue(), OperAct.DISTRIBUTE.getValue(), objectId, objectType+" 权限分配");
		
		
		}else if(StringUtils.isNotBlank(objectType) && ConstantWebApp.OPER_CODE_ADMIN.equals(objectType)){
//			adminOperRelaService.saveAllAuthCodeByAdminId(objectId,objectType,authJsonText);
			
			adminOperRelaService.deleteAdminAuth(objectId);
			List<AdminOperRela> list = OperCodeJSONUtil.getAdminAuth(authJsonText, objectId, objectType);
			List<AdminOperRela> cats = new ArrayList<AdminOperRela>();
			List<AdminOperRela> others = new ArrayList<AdminOperRela>();
			for(AdminOperRela re: list){
				if(ConstantOperCode.AUTH_CAT_TYPE.equals(re.getOperTargetType())){
					cats.add(re);
				}else{
					others.add(re);
				}
			}
			adminOperRelaService.save(others);
			adminOperRelaService.save(cats);
			jsonText = "{flag:true,msg:'\u7ba1\u7406\u5458\u6743\u9650\u8c03\u6574\u6210\u529f'}";
			addLog(Module.SYSTEM.getValue(), OperAct.DISTRIBUTE.getValue(), objectId, objectType+" 权限分配");
			
		}else{
			jsonText = "{flag:false,msg:'\u6743\u9650\u6dfb\u52a0\u5f02\u5e38'}";
		}	
		return renderText(jsonText);
	}
	
	
	
	
	/**
	 *   初始化权限，写入数据库
	 */
	@SuppressWarnings("unused")
	private void initOperCaoes(){
		try {
			operCodeService.bathSaveOperCode(ReadOperCodeXML.loadOperCodes());
		} catch (Exception e) {
			// 使用log日志写法 to 朱晓栋(此方法只为权限初始化使用)
			e.printStackTrace();
		} 
	}

	public List<List<OperCode>> getCodeList() {
		return codeList;
	}

	public void setCodeList(List<List<OperCode>> codeList) {
		this.codeList = codeList;
	}

	public String getObjectType() {
		return objectType;
	}

	public void setObjectType(String objectType) {
		this.objectType = objectType;
	}

	public String getObjectId() {
		return objectId;
	}

	public void setObjectId(String objectId) {
		this.objectId = objectId;
	}

	public String getAuthJsonText() {
		return authJsonText;
	}

	public void setAuthJsonText(String authJsonText) {
		this.authJsonText = authJsonText;
	}

	public String getJsonText() {
		return jsonText;
	}

	public void setJsonText(String jsonText) {
		this.jsonText = jsonText;
	}
	
	
	public static Map<String ,List<OperCodeCheckBean>>  map = new HashMap<String, List<OperCodeCheckBean>>();
	public Map<String ,List<OperCodeCheckBean>>   loadAuthCheckMapInfo() { 
		if(!map.isEmpty()) return map;
		List<OperCodeCheckBean> list = new ArrayList<OperCodeCheckBean>();
		loadAuthCheckInfo(list,"hasau","phocha", "objectType", ConstantWebApp.OPER_CODE_ROLE,ConstantOperCode.GOBLE_ROLE,ConstantOperCode.AUTH_GOBLE_TYPE);
		loadAuthCheckInfo(list,null,null, "objectType", ConstantWebApp.OPER_CODE_ADMIN,ConstantOperCode.GOBLE_ADMIN,ConstantOperCode.AUTH_GOBLE_TYPE);
		map.put("saveAuthCode", list); //key：action方法名		
		return map;
	}
	
	 
}